<template>
  <div class="feedback-container">
    <div class="header">
      <div class="left">
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedFeedbacks.length">
          批量删除
        </el-button>
      </div>
      <div class="right">
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="反馈类型">
          <el-select v-model="searchForm.type" placeholder="请选择反馈类型" clearable>
            <el-option label="功能建议" :value="1" />
            <el-option label="问题反馈" :value="2" />
            <el-option label="其他" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable>
            <el-option label="待处理" :value="0" />
            <el-option label="处理中" :value="1" />
            <el-option label="已处理" :value="2" />
            <el-option label="已关闭" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 反馈列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="feedbackList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="反馈标题" min-width="200" />
        <el-table-column prop="type" label="反馈类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getFeedbackTypeTag(row.type)">
              {{ getFeedbackTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="提交人" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status !== 3"
              type="primary"
              link
              @click="handleReply(row)"
            >
              回复
            </el-button>
            <el-button
              v-if="row.status !== 3"
              type="success"
              link
              @click="handleUpdateStatus(row)"
            >
              更新状态
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复反馈对话框 -->
    <el-dialog
      v-model="replyDialog.visible"
      title="回复反馈"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="replyFormRef"
        :model="replyDialog.form"
        :rules="replyDialog.rules"
        label-width="100px"
      >
        <el-form-item label="反馈标题">
          <span>{{ replyDialog.data.title }}</span>
        </el-form-item>
        <el-form-item label="反馈内容">
          <div class="content">{{ replyDialog.data.content }}</div>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input
            v-model="replyDialog.form.reply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="replyDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleReplySubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialog.visible"
      title="更新状态"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="statusFormRef"
        :model="statusDialog.form"
        :rules="statusDialog.rules"
        label-width="100px"
      >
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(statusDialog.data.status)">
            {{ getStatusLabel(statusDialog.data.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusDialog.form.status" placeholder="请选择新状态">
            <el-option label="待处理" :value="0" />
            <el-option label="处理中" :value="1" />
            <el-option label="已处理" :value="2" />
            <el-option label="已关闭" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleStatusSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看反馈对话框 -->
    <el-dialog
      v-model="viewDialog.visible"
      title="反馈详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="feedback-detail">
        <div class="detail-item">
          <span class="label">反馈标题：</span>
          <span class="value">{{ viewDialog.data.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">反馈类型：</span>
          <span class="value">
            <el-tag :type="getFeedbackTypeTag(viewDialog.data.type)">
              {{ getFeedbackTypeLabel(viewDialog.data.type) }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">提交人：</span>
          <span class="value">{{ viewDialog.data.userName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">联系方式：</span>
          <span class="value">{{ viewDialog.data.contact || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">处理状态：</span>
          <span class="value">
            <el-tag :type="getStatusTag(viewDialog.data.status)">
              {{ getStatusLabel(viewDialog.data.status) }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">提交时间：</span>
          <span class="value">{{ viewDialog.data.createTime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">反馈内容：</span>
          <div class="content">{{ viewDialog.data.content }}</div>
        </div>
        <div class="detail-item" v-if="viewDialog.data.reply">
          <span class="label">回复内容：</span>
          <div class="content">{{ viewDialog.data.reply }}</div>
        </div>
        <div class="detail-item" v-if="viewDialog.data.reply">
          <span class="label">回复人：</span>
          <span class="value">{{ viewDialog.data.replyUserName }}</span>
        </div>
        <div class="detail-item" v-if="viewDialog.data.reply">
          <span class="label">回复时间：</span>
          <span class="value">{{ viewDialog.data.replyTime }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="viewDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getFeedbackList,
  replyFeedback,
  updateFeedbackStatus,
  deleteFeedback,
  batchDeleteFeedback,
  getFeedbackDetail
} from '@/api/feedback'

// 搜索表单
const searchForm = reactive({
  type: '',
  status: ''
})

// 分页参数
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 反馈列表数据
const feedbackList = ref([])
const loading = ref(false)
const selectedFeedbacks = ref([])

// 回复反馈对话框
const replyDialog = reactive({
  visible: false,
  data: {},
  form: {
    reply: '',
    replyUserId: 1 // 这里暂时使用固定值1，实际应该使用当前登录用户的ID
  },
  rules: {
    reply: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
  }
})

// 更新状态对话框
const statusDialog = reactive({
  visible: false,
  data: {},
  form: {
    status: ''
  },
  rules: {
    status: [{ required: true, message: '请选择新状态', trigger: 'change' }]
  }
})

// 查看反馈对话框
const viewDialog = reactive({
  visible: false,
  data: {}
})

// 获取反馈列表
const fetchFeedbackList = async () => {
  loading.value = true
  try {
    const res = await getFeedbackList({
      pageNum: page.current,
      pageSize: page.size,
      ...searchForm
    })
    feedbackList.value = res.data.records
    page.total = res.data.total
  } catch (error) {
    console.error('获取反馈列表失败:', error)
    ElMessage.error('获取反馈列表失败')
  } finally {
    loading.value = false
  }
}

// 回复反馈
const handleReply = (row) => {
  replyDialog.data = row
  replyDialog.form.reply = ''
  replyDialog.visible = true
}

// 提交回复
const handleReplySubmit = async () => {
  try {
    await replyFeedback(replyDialog.data.id, replyDialog.form)
    ElMessage.success('回复成功')
    replyDialog.visible = false
    fetchFeedbackList()
  } catch (error) {
    console.error('回复反馈失败:', error)
    ElMessage.error('回复反馈失败')
  }
}

// 更新状态
const handleUpdateStatus = (row) => {
  statusDialog.data = row
  statusDialog.form.status = row.status
  statusDialog.visible = true
}

// 提交状态更新
const handleStatusSubmit = async () => {
  try {
    await updateFeedbackStatus(statusDialog.data.id, statusDialog.form.status)
    ElMessage.success('状态更新成功')
    statusDialog.visible = false
    fetchFeedbackList()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 查看反馈
const handleView = async (row) => {
  try {
    const res = await getFeedbackDetail(row.id)
    viewDialog.data = res.data
    viewDialog.visible = true
  } catch (error) {
    console.error('获取反馈详情失败:', error)
    ElMessage.error('获取反馈详情失败')
  }
}

// 删除反馈
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该反馈吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFeedback(row.id)
      ElMessage.success('删除成功')
      fetchFeedbackList()
    } catch (error) {
      console.error('删除反馈失败:', error)
      ElMessage.error('删除反馈失败')
    }
  })
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedFeedbacks.value.length) {
    ElMessage.warning('请选择要删除的反馈')
    return
  }
  ElMessageBox.confirm('确定要删除选中的反馈吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteFeedback(selectedFeedbacks.value.map(item => item.id))
      ElMessage.success('批量删除成功')
      fetchFeedbackList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedFeedbacks.value = selection
}

// 搜索
const handleSearch = () => {
  page.current = 1
  fetchFeedbackList()
}

// 重置搜索
const handleReset = () => {
  searchForm.type = ''
  searchForm.status = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  page.size = val
  fetchFeedbackList()
}

// 页码改变
const handleCurrentChange = (val) => {
  page.current = val
  fetchFeedbackList()
}

// 获取反馈类型标签
const getFeedbackTypeTag = (type) => {
  const map = {
    1: 'success',
    2: 'warning',
    3: 'info'
  }
  return map[type] || 'info'
}

// 获取反馈类型标签文本
const getFeedbackTypeLabel = (type) => {
  const map = {
    1: '功能建议',
    2: '问题反馈',
    3: '其他'
  }
  return map[type] || '未知类型'
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const map = {
    0: '待处理',
    1: '处理中',
    2: '已处理',
    3: '已关闭'
  }
  return map[status] || '未知状态'
}

onMounted(() => {
  fetchFeedbackList()
})
</script>

<style scoped>
.feedback-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form :deep(.el-select) {
  width: 200px;
}

.list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.feedback-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.detail-item .content {
  margin-top: 10px;
  white-space: pre-wrap;
  line-height: 1.5;
}
</style> 